<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               :title="hasID === true? $t('update')+'非物联设备' : $t('add')+'非物联设备'"
               :modal="false"
               class="user-dialog add-or-updata"
               width="70%"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="dataForm"
               v-loading="dataListLoading"
               :element-loading-text="$t('loading')"
               ref="dataForm"
               label-position="left"
               @keyup.enter.native="dataFormSubmitHandle()"
               label-width="120px">
        <!-- <div> -->
        <div class="content">
          <div class="title">重要信息</div>
          <div class="line"></div>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="deviceId"
                          label="设备ID">
              <el-input v-model.trim="dataForm.deviceId"
                        @change="val => dataForm.deviceId = val"
                        :disabled='hasID === true'
                        maxlength="20"
                        show-word-limit
                        placeholder="填写或者系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="name"
                          label="设备名称"
                          :rules="required()">
              <el-input v-model.trim="dataForm.name"
                        maxlength="20"
                        show-word-limit
                        placeholder="请输入设备名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="subsystem"
                          label="所属子系统"
                          :rules="required()">
              <el-select v-model="dataForm.subsystem"
                         clearable
                         multiple
                         style="width:100%"
                         placeholder="请选择所属子系统">
                <el-option v-for="item in currentAppMenu"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="deviceType"
                          label="设备类型"
                          :rules="required()">
              <el-select v-model="dataForm.deviceType"
                         clearable
                         :disabled='hasID === true'
                         style="width:100%"
                         placeholder="请选择设备类型">
                <el-option v-for="item in $store.state.EquTypeList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="marks"
                          label="设备描述">
              <el-input type="textarea"
                        maxlength="200"
                        show-word-limit
                        :autosize="{ minRows: 3, maxRows: 4}"
                        placeholder="请输入内容"
                        v-model="dataForm.marks">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备照片"
                          prop="url">
              <file-upload reg=".(png|jpeg|jpg)$"
                           ref="fileUpload"
                           accept=".jpeg,.jpg,.png"
                           title="上传图片"
                           :limit="3"
                           v-model="dataForm.url"
                           :paramData="{bucketName:'EquList/images'}"
                           action="/springbootApi/system/oss/upload"
                           uploadType="picture-card"
                           @success="successImgLoad"
                           @remove="handleImgRemove" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="content">
          <div class="title">基础信息</div>
          <div class="line"></div>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="type"
                          label="产品类型">
              <el-select v-model="dataForm.type"
                         clearable
                         style="width:100%"
                         placeholder="请选择产品类型">
                <el-option v-for="item in productTypeList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="model"
                          label="设备型号">
              <el-input v-model.trim="dataForm.model"
                        maxlength="20"
                        show-word-limit
                        placeholder="请输入设备型号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="brandId"
                          :rules="required()"
                          label="品牌">
              <el-select v-model="dataForm.brandId"
                         clearable
                         style="width:100%"
                         placeholder="请选择设备品牌">
                <el-option v-for="item in brandList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="aid"
                          label="所在位置">
              <el-select v-model="dataForm.aid"
                         clearable
                         filterable
                         style="width:100%"
                         placeholder="请选择所在位置">
                <el-option v-for="item in locationList"
                           :key="item.id"
                           :label="item.allName"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="content">
          <div class="title">供应商信息</div>
          <div class="line"></div>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="supplier"
                          label="供应商名称">
              <el-input v-model.trim="dataForm.supplier"
                        maxlength="20"
                        show-word-limit
                        placeholder="请输入设备供应商"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="linkMan"
                          label="联系人">
              <el-input v-model.trim="dataForm.linkMan"
                        maxlength="10"
                        show-word-limit
                        placeholder="请输入设备厂商联系人姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="link"
                          label="联系电话"
                          :rules="phoneAndMobileRuleCanNull()">
              <el-input v-model.trim="dataForm.link"
                        show-word-limit
                        placeholder="请输入设备厂商联系人电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- </div> -->
      </el-form>
      <template slot="footer">
        <el-button @click="closeDialog()">{{ $t("cancel") }}</el-button>
        <el-button type="primary"
                   :loading="dataListLoading"
                   @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import fileUpload from '@/components/file-upload/file-upload'
export default {
  mixins: [mixinViewModule, minFormValidate],
  data () {
    return {
      mixinViewModuleOptions: {
        deleteImgURL: '/system/oss/delete',
        getDataListURL: '', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        addURL: 'tb/device/insertDevice', // 添加或修改接口，API地址
        updateURL: 'tb/device/updateDevice', // 添加或修改接口，API地址
        getDataInfoURL: 'tb/device/getDevice?id=', // 数据详情，API地址
        deleteURL: '', // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      tempDeleteFileList: [], // 临时删除的文件
      newEditFileList: [], // 保存在编辑时新增的文件路径
      newThumbnailList: [], // 保存在编辑时新增的thumbnail图路径
      tempThumbnailList: [], // 临时删除的thumbnail图的图片
      visible: false,
      brandList: [],
      dataForm: {
        aid: '',
        link: '',
        linkMan: '',
        marks: '',
        subsystem: [],
        supplier: '',
        template: '',
        type: '',
        url: [],
        brandId: '',
        name: '',
        deviceType: '',
        deviceId: ''
      },
      currentAppMenu: [{ id: 4, name: '会务管理系统' }, // 所属子系统
        { id: 1, name: '宿舍管理系统' },
        { id: 7, name: '访客管理系统' },
        { id: 2, name: '智慧路灯系统' },
        { id: 3, name: '多媒体管理系统' },
        { id: 5, name: '餐饮管理系统' },
        { id: 6, name: '能耗管理系统' },
        { id: 0, name: '集成管理系统' },
        { id: 8, name: '视频监控系统' },
        { id: 9, name: '健身房管理系统' },
        { id: 10, name: '门禁管理系统' }],
      productTypeList: [{ // 产品类型
        id: 1,
        name: '网关设备'
      }, {
        id: 2,
        name: '网关子设备'
      }, {
        id: 3,
        name: '直连设备'
      }],
      EquTempList: [],
      locationList: [], // 所在位置
      hasID: false
    }
  },
  components: {
    fileUpload
  },
  mounted () {
    this.$http.get('tb/deviceBrand/getAll').then(({ data: res }) => {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.brandList = res.data
    })
  },
  methods: {
    init (data) {
      if (data) {
        this.dataForm = data
        this.dataForm.subsystem = typeof data.subsystem === 'string' ? data.subsystem.split(',').map(Number) : [] // 回显所属子系统
        this.hasID = true
      } else {
        this.hasID = false
      }
      this.$nextTick(() => {
        this.getAllNameList()
        if (this.dataForm.id) {
          let temp = []
          temp.push(this.dataForm.id)
          this.$http.get('tb/device/getDevice?id=' + this.dataForm.id).then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            // this.dataForm = res.data
            let list = []
            for (let i = 0; i < res.data.url.length; i++) {
              let arr = {}
              arr.name = res.data.url[i]
              arr.url = res.data.url[i]
              list.push(arr)
            }
            if (res.data.url) {
              if (this.$refs.fileUpload) {
                this.$refs.fileUpload.init(list)
              }
            }
          })
        }
      })
      this.visible = true
    },
    onchange (val) {
      console.log(val)
    },
    getAllNameList () {
      this.$http.get('tb/area/allNameList').then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.locationList = res.data
      })
    },
    closeDialog () {
      this.dataForm.deviceId = ''
      this.dataForm.id = ''
      this.dataForm.name = ''
      this.dataForm.subsystem = []
      this.dataForm.template = ''
      this.dataForm.marks = ''
      this.dataForm.url = []
      this.dataForm.type = ''
      this.dataForm.model = ''
      this.dataForm.brandId = ''
      this.dataForm.aid = ''
      this.dataForm.supplier = ''
      this.dataForm.linkMan = ''
      this.dataForm.link = ''
      this.dataForm.deviceType = ''
      this.$emit('callBack')
      this.visible = false
    },
    handleImgRemove (url) {
      let index = this.dataForm.url.findIndex(item => item === url.url)
      this.dataForm.url.splice(index, 1)
      return this.deleteData({
        url: this.mixinViewModuleOptions.deleteImgURL,
        paramData: { files: url.url },
        isLoading: false
      })
    },
    successImgLoad (name, url) {
      // let temp = []
      // temp.push(url)
      // this.dataForm.url = temp
      this.dataForm.url.push(url)
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            const url = this.hasID === true ? this.mixinViewModuleOptions.updateURL
              : this.mixinViewModuleOptions.addURL
            if (this.hasID === false) {
              let arr = {}
              arr.deviceId = this.dataForm.deviceId
              arr.name = this.dataForm.name
              arr.subsystem = this.dataForm.subsystem.join()
              // arr.template = this.dataForm.template
              arr.deviceType = this.dataForm.deviceType
              arr.marks = this.dataForm.marks
              arr.url = this.dataForm.url
              arr.type = this.dataForm.type
              arr.model = this.dataForm.model
              arr.brandId = this.dataForm.brandId
              arr.aid = this.dataForm.aid
              arr.supplier = this.dataForm.supplier
              arr.linkMan = this.dataForm.linkMan
              arr.link = this.dataForm.link
              arr.iot = 0
              arr.energy = 0
              this.$http.post(url, arr).then(({ data: res }) => {
                if (res.code !== 0) {
                  return this.$message.error(res.msg)
                }
                this.$message.success('新增成功')
                this.closeDialog()
              })
            } else {
              let arr = {}
              arr.id = this.dataForm.id
              arr.deviceId = this.dataForm.deviceId
              arr.name = this.dataForm.name
              arr.subsystem = this.dataForm.subsystem.join()
              // arr.template = this.dataForm.template
              arr.deviceType = this.dataForm.deviceType
              arr.marks = this.dataForm.marks
              arr.url = this.dataForm.url
              arr.type = this.dataForm.type
              arr.model = this.dataForm.model
              arr.brandId = this.dataForm.brandId
              arr.aid = this.dataForm.aid
              arr.supplier = this.dataForm.supplier
              arr.linkMan = this.dataForm.linkMan
              arr.link = this.dataForm.link
              arr.creator = this.dataForm.creator
              arr.createDate = this.dataForm.createDate
              arr.iot = this.dataForm.iot
              arr.energy = 0
              arr.status = this.dataForm.status
              arr.applyOa = this.dataForm.applyOa
              this.$http.put(url, arr).then(({ data: res }) => {
                if (res.code !== 0) {
                  return this.$message.error(res.msg)
                }
                this.$message.success('保存成功')
                this.closeDialog()
              })
            }
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    )
  }
}
</script>

<style lang="scss" scoped>
.label-left-form {
  display: flex;
}
.content {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  margin-bottom: 10px;

  .title {
    min-width: 80px;
    margin: 0 10px;
    vertical-align: -8%;
  }

  .line {
    width: 100%;
    border-top: 1px solid #ccc;
  }
}
</style>
